<template>
  <div>
    <div class="my-container">
      <div style="text-align: center;">
        <h3>学生信息列表</h3>
      </div>
      <div style="margin: 20px 0">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="dialogVisible = true" plain>新增</el-button>
        <el-button type="primary" size="small" icon="el-icon-edit" @click="showUpdate()" plain>修改</el-button>
        <el-button type="primary" size="small" icon="el-icon-delete" @click="deleteStudent()" plain>删除</el-button>
        <el-button type="primary" size="small" icon="el-icon-success" @click="openStatus()" plain>启用</el-button>
        <el-button type="primary" size="small" icon="el-icon-error" @click="closeStatus()" plain>禁用</el-button>
        <el-button type="primary" size="small" icon="el-icon-upload" @click="centerDialogVisible = true" plain>导入</el-button>
        <el-button type="primary" size="small" icon="el-icon-download" @click="exportStudent()" plain>导出</el-button>
      </div>
      <el-table :data="studentList" stripe style="width: 100%" ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="number" label="学生学号"/>
        <el-table-column prop="name" label="学生姓名"/>
        <el-table-column prop="sex" label="学生性别" width="120" align="center">
          <template slot-scope="scope">{{ scope.row.sex === 1 ? '男' : '女' }}</template>
        </el-table-column>
        <el-table-column prop="birthday" label="出生日期" :formatter='dateFormat'/>
        <el-table-column prop="age" label="学生年龄" width="120" align="center"/>
        <el-table-column prop="dormitoryName" label="学生宿舍"/>
        <el-table-column prop="sex" label="学生状态">
          <template slot-scope="scope">{{ scope.row.recordStatus === 1 ? '启用' : '禁用' }}</template>
        </el-table-column>
        <el-table-column prop="className" label="学生班级"/>
        <el-table-column prop="gradeName" label="学生年级"/>
        <el-table-column prop="collegeName" label="学生学院"/>
      </el-table>
    </div>
    <!-- 新增弹窗 -->
    <el-dialog title="新增学生信息" :visible.sync="dialogVisible" width="50%">
      <el-form ref="form" :model="student" label-width="180px">
        <el-form-item label="学生学号：">
          <el-input v-model="student.number"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名：">
          <el-input v-model="student.name"></el-input>
        </el-form-item>
        <el-form-item label="学生性别：">
          <el-radio-group v-model="student.sex">
            <el-radio label="1" >男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期：">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="student.birthday" value-format="timestamp" style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="学生年龄：">
          <el-input v-model="student.age"></el-input>
        </el-form-item>
        <el-form-item label="学生宿舍：">
          <el-input v-model="student.dormitoryName"></el-input>
        </el-form-item>
        <el-form-item label="班级名称：">
          <el-input v-model="student.className"></el-input>
        </el-form-item>
        <el-form-item label="年级名称：">
          <el-input v-model="student.gradeName"></el-input>
        </el-form-item>
        <el-form-item label="学院名称：">
          <el-input v-model="student.collegeName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">保 存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改弹窗 -->
    <el-dialog title="修改学生信息" :visible.sync="dialogVisibleUpdate" width="50%">
      <el-form ref="form" :model="student" label-width="180px">
        <el-form-item label="学生学号：">
          <el-input v-model="student.number"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名：">
          <el-input v-model="student.name"></el-input>
        </el-form-item>
        <el-form-item label="学生性别：">
          <el-radio-group v-model="student.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期：">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="student.birthday" value-format="timestamp" style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="学生年龄：">
          <el-input v-model="student.age"></el-input>
        </el-form-item>
        <el-form-item label="学生宿舍：">
          <el-input v-model="student.dormitoryName"></el-input>
        </el-form-item>
        <el-form-item label="班级名称：">
          <el-input v-model="student.className"></el-input>
        </el-form-item>
        <el-form-item label="年级名称：">
          <el-input v-model="student.gradeName"></el-input>
        </el-form-item>
        <el-form-item label="学院名称：">
          <el-input v-model="student.collegeName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onUpdate">保 存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 导入弹窗 action	必选参数上传的地址/ multiple	是否支持多选文件/ limit	最大允许上传个数-->
    <el-dialog title="上传文件" :visible.sync="centerDialogVisible" width="30%" center>
      <el-upload
          class="upload-demo"
          ref="upload"
          action="http://10.18.8.232:8991/student/importStudentList"
          :before-upload="beforeUpload"
          :on-preview="onPreview"
          :on-remove="onRemove"
          :on-success="onSuccess"
          :on-error="onError"
          :file-list="fileList"
          :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过500kb</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="centerDialogVisible = false">取 消</el-button>
        <el-button size="small" type="info" @click="centerDialogVisible = false">模板下载</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
// 按需导入 API 接口
import { getStudentList, saveStudent, getStudentOne, editStudent, deleteStudent, openRecordStatus, closeRecordStatus } from '@/api/studentList'

// 导入需要的组件

export default {
  name: 'StudentList',
  // 注册组件
  components: {

  },
  data() {
    return {
      fileList: [],

      dialogVisible: false,
      studentId: '',
      dialogVisibleUpdate: false,
      centerDialogVisible: false,
      multipleSelection: [],
      studentList: [],
      student: {
        id: '',
        number: '',
        name: '',
        sex: '1',
        birthday: '',
        age: '',
        dormitoryName: '',
        className: '',
        gradeName: '',
        collegeName: ''
      }
    }
  },
  created() {
    this.initStudentList()
  },
  methods: {
    // 文件上传失败时的钩子
    onError() {
      this.centerDialogVisible = false
      this.fileList = []
    },
    // 文件上传成功时的钩子
    onSuccess(response, file, fileList) {
      console.log("===============================")
      console.log(response)
      console.log(file)
      console.log(fileList)
      console.log("===============================")
      this.centerDialogVisible = false
      this.fileList = []
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      if (!(file.name.endsWith(".xls") || file.name.endsWith(".xlsx"))) {
        this.$alert('导入失败，上传的文件格式必须是.xls或.xlsx!', '提示', {
          confirmButtonText: '确定',
          type: 'error'
        });
        return;
      }
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 文件列表移除文件时的钩子
    onRemove(file, fileList) {
      console.log("================handleRemove===============")
      console.log(file, fileList);
      console.log("===============================")
    },
    // 点击已上传的文件链接时的钩子
    onPreview(file) {
      console.log("================handlePreview===============")
      console.log(file);
      console.log("===============================")
    },
    //时间格式化-S
    dateFormat(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },

    async initStudentList() {
      const { data: res } = await getStudentList();
      if (res.code == 200) {
        this.studentList = res.data
      }
    },

    async onSubmit() {
      const { data: res } = await saveStudent(this.student);
      if (res.code == 200) {
        this.dialogVisible = false;
        this.student = {};
        this.initStudentList();
      }
    },

    async showUpdate() {
      if (this.multipleSelection.length == 0) {
        this.$alert('请选择要修改的数据！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }

      if (this.multipleSelection.length > 1) {
        this.$alert('请选择一条记录进行修改！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }

      if (this.multipleSelection.length == 1) {
        const { data: res } = await getStudentOne(this.multipleSelection[0].id);
        if (res.code == 200) {
          this.student = res.data;
          this.dialogVisibleUpdate = true;
        } else {
          this.$confirm('系统异常，请联系管理员！', '提示', {
            confirmButtonText: '确定',
            type: 'error'
          });
        }
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      // this.studentId = val[0].id;
    },

    async onUpdate() {
      const { data: res } = await editStudent(this.student);
      if (res.code == 200) {
        this.dialogVisibleUpdate = false;
        this.student = {};
        this.initStudentList();
      }
    },

    deleteStudent() {
      if (this.multipleSelection.length == 0) {
        this.$alert('请选择要删除的数据！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }

      if (this.multipleSelection.length > 1) {
        this.$alert('请选择一条记录进行删除！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }

      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let ids = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id);
        }

        const { data: res } = await deleteStudent(ids);
        if (res.code == 200) {
          this.initStudentList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    openStatus() {
      if (this.multipleSelection.length == 0) {
        this.$alert('请选择要启用的数据！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }

      this.$confirm('此操作将会启用的该数据！, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let ids = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id);
        }

        const { data: res } = await openRecordStatus(ids);
        if (res.code == 200) {
          this.initStudentList();
          this.$message({
            type: 'success',
            message: '启用成功!'
          });
        }
      });
    },

    closeStatus () {
      if (this.multipleSelection.length == 0) {
        this.$alert('请选择要禁用的数据！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }

      this.$confirm('此操作将会禁用的该数据！, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let ids = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id);
        }

        const { data: res } = await closeRecordStatus(ids);
        if (res.code == 200) {
          this.initStudentList();
          this.$message({
            type: 'success',
            message: '禁用成功!'
          });
        }
      });
    },

    exportStudent() {
      window.open("http://10.18.8.232:8991/student/exportStudentList")
    }
  }
}
</script>

<style lang="less" scoped>
.my-container {
  width: 80%;
  background-color: #f5f6f7;
  margin: auto;
  padding: 10px 20px
}
</style>
